package com.ec.as.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ec.as.domain.dto.LeaveRequestDTO;
import com.ec.as.domain.dto.LeaveRequestQueryDTO;
import com.ec.as.domain.po.LeaveRequest;
import com.ec.as.mapper.LeaveRequestMapper;
import com.ec.as.service.LeaveRequestService;
import com.ec.common.domain.PageVO;
import com.ec.common.domain.Result;
import com.ec.common.utils.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class LeaveRequestServiceImpl implements LeaveRequestService {

    private static final Logger logger = LoggerFactory.getLogger(LeaveRequestServiceImpl.class);

    @Resource
    private LeaveRequestMapper leaveRequestMapper;

    @Override
    public Result<LeaveRequest> submitLeaveRequest(LeaveRequestDTO dto) {
        // 验证请假类型
        if (!isValidReasonType(dto.getReasonType())) {
            return Result.error("无效的请假类型");
        }
        // 当类型为 other 时，reasonDetails 不能为空
        if ("other".equals(dto.getReasonType()) && (dto.getReasonDetails() == null || dto.getReasonDetails().isEmpty())) {
            return Result.error("其他类型请假必须提供具体原因");
        }
        // 验证时间
        if (dto.getStartTime().isAfter(dto.getEndTime())) {
            return Result.error("开始时间不能晚于结束时间");
        }

        LeaveRequest entity = new LeaveRequest();
        BeanUtils.copyProperties(dto, entity);
        entity.setStatus("pending");
        entity.setCreatedAt(LocalDateTime.now());
        try{
            leaveRequestMapper.insert(entity);
            return Result.ok(entity);
        }catch (Exception e){
            logger.error("插入请假申请失败",e);
            return Result.error("插入请假申请失败");
        }
    }

    @Override
    public Result<Void> cancelPendingLeaveRequest(Long id) {
        LeaveRequest request = leaveRequestMapper.selectById(id);
        if (request == null) {
            return Result.error("申请不存在");
        }
        if (!"pending".equals(request.getStatus())) {
            return Result.error("只能取消待审核的申请");
        }
        request.setStatus("cancelled");
        leaveRequestMapper.updateById(request);
        return Result.ok();
    }

    @Override
    public Result<Void> submitCancelApprovedLeaveRequest(Long id) {
        LeaveRequest request = leaveRequestMapper.selectById(id);
        if (request == null) {
            return Result.error("申请不存在");
        }
        if (!"approved".equals(request.getStatus())) {
            return Result.error("只能对已批准的申请提交取消");
        }
        // 标记为待取消审核
        request.setStatus("on_leave"); // 假设新增一个中间状态
        leaveRequestMapper.updateById(request);
        return Result.ok();
    }

    @Override
    public Result<Void> reviewLeaveRequest(Long id, boolean approve, Integer adminId) {
        LeaveRequest request = leaveRequestMapper.selectById(id);
        if (request == null) {
            return Result.error("申请不存在");
        }
        if (!"pending".equals(request.getStatus())) {
            return Result.error("只能审核待审核的申请");
        }
        request.setStatus(approve ? "approved" : "rejected");
        request.setApprovedByAdminId(adminId);
        leaveRequestMapper.updateById(request);
        return Result.ok();
    }

    @Override
    public Result<Void> reviewCancelRequest(Long id, boolean approve, Integer adminId) {
        LeaveRequest request = leaveRequestMapper.selectById(id);
        if (request == null) {
            return Result.error("申请不存在");
        }
        if (!"on_leave".equals(request.getStatus())) {
            return Result.error("只能审核待取消的申请");
        }
        request.setStatus(approve ? "cancelled" : "approved"); // 拒绝取消，恢复批准状态
        request.setApprovedByAdminId(adminId);
        leaveRequestMapper.updateById(request);
        return Result.ok();
    }

    @Override
    public Result<PageVO<LeaveRequest>> listLeaveRequests(LeaveRequestQueryDTO queryDTO) {
        try{
            LambdaQueryWrapper<LeaveRequest> wrapper = new LambdaQueryWrapper<>();
            //筛选用户id
            if (queryDTO.getElderlyUserId() != null) {
                wrapper.eq(LeaveRequest::getElderlyUserId, queryDTO.getElderlyUserId());
            }
            //筛选是否有请假类型
            if (queryDTO.getReasonType() != null && !queryDTO.getReasonType().isEmpty()) {
                wrapper.eq(LeaveRequest::getReasonType, queryDTO.getReasonType());
            }
            if (queryDTO.getStatus() != null && !queryDTO.getStatus().isEmpty()) {
                wrapper.eq(LeaveRequest::getStatus, queryDTO.getStatus());
            }
            Page<LeaveRequest> page = new Page<>(queryDTO.getPageNo(), queryDTO.getPageSize());
            page = leaveRequestMapper.selectPage(page, wrapper);
            return Result.ok(PageVO.of(page));
        }catch (Exception e){
            logger.error("查询请假申请列表失败",e);
            return Result.error("查询请假申请列表失败");
        }
    }

    private boolean isValidReasonType(String reasonType) {
        return "medical".equals(reasonType) || "family_reunion".equals(reasonType) ||
                "personal_affairs".equals(reasonType) || "other".equals(reasonType);
    }
}